package com.iflytek.hive.step1mapjoin;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.net.URI;

public class MapJoinDriver extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        if (args.length < 2) {
            args = new String[2];
            args[0] = "D:\\桌面\\SJB\\Idea\\sales\\datas\\input\\input_hive\\tbSaleDetail.txt";
            args[1] = "D:\\桌面\\SJB\\Idea\\sales\\datas\\output\\output_hive\\step1mapjoin";
        }

        // 1:获取job对象
        Job job = Job.getInstance(super.getConf(), "step1mapjoin_job");
        // 2:设置job对象(将小表放在分布式缓存中)
            // 将小表放在分布式缓存中
            // job.addCacheFile(new URI("hdfs://hadoop102:8020/cache_file/product.txt"));
            job.addCacheFile(new URI("file:///桌面/06-Hive/hive案例数据/tbSale.txt"));
            job.addCacheFile(new URI("file:///桌面/06-Hive/hive案例数据/tbdate.txt"));
            // 第一步:设置输入类和输入的路径
            job.setInputFormatClass(TextInputFormat.class);
            TextInputFormat.addInputPath(job, new Path(args[0]));
            // 第二步:设置Mapper类和数据类型
            job.setMapperClass(MapJoinMapper.class);
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(NullWritable.class);
            // 设置ruducer个数为0
            job.setNumReduceTasks(0);
            // 第八步:设置输出类和输出路径
            job.setOutputFormatClass(TextOutputFormat.class);
            TextOutputFormat.setOutputPath(job, new Path(args[1]));

        // 判断输出路径是否存在 如果存在删除
        FileSystem fs = FileSystem.get(getConf());
        if (fs.exists(new Path(args[1]))) {
            fs.delete(new Path(args[1]), true);
        }
        // 3:等待任务结束
        boolean bl = job.waitForCompletion(true);
        return bl ? 0 : 1;

    }
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        // 启动job任务
        int run = ToolRunner.run(configuration, new MapJoinDriver(), args);
        System.exit(run);
    }
}